<?php
date_default_timezone_set('PRC');
session_start();

$result = [
    'status' => 0,
    'data' => null,
    'message' => '未知错误'
];

include_once '../mysql/sql.php';
include_once 'select-fun.php';

if (isset($_SESSION['userid'])) {
    if (isset($sql) && $sql) {
        $params = [
            'userid' => $_SESSION['userid']
        ];

        $params['scope'] = isset($_GET['scope']) ? $_GET['scope'] : 'day';
        $params['incspe'] = isset($_GET['incspe']) ? $_GET['incspe'] : 0;
        $params['date'] = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
        
        $list = incspe_list($mysql, $params);
        if ($list) {
            $result['status'] = 1;
            $result['data'] = format($list);
            $result['message'] = '获取数据成功';
        }
        else if ($list === null) {
            $result['status'] = 1;
            $result['data'] = null;
            $result['message'] = '数据为空';
        }
        else {
            $result['status'] = 0;
            $result['message'] = '获取数据失败';
        };

        // 关闭连接
        $mysql->close();
    }
    else {
        $result['message'] = '数据库连接错误';
    };
}
else {
    $result['message'] = '用户未登入';
};

echo json_encode($result);

// 数据格式
function format($arr) {
    $result = [
        'total_inc' => null,
        'total_spe' => null,
        'item' => []
    ];
    foreach ($arr as $key => $value) {
        if ($value['incspecode'] == 'total_inc' || $value['incspecode'] == 'total_spe') {
            $result[$value['incspecode']] = $value['money'];
        }
        else {
            array_push($result['item'], $value);
        };
    };
    if (count($result['item']) == 0) {
        $result['item'] = null;
    };
    return $result;
};
?>